directives.directive('editTableAggregate',['$rootScope','tools','$timeout',function($rootScope,tools,$timeout){
    return {
        restrict: 'AE',
        scope: {},
        replace: true,
        templateUrl: '/trend-new-BI/app/components/dbManager/editTableAggregate/editTableAggregateView.html',
        link: function(scope, element, attr){
            scope.refTableDesc = '';
            scope.parentTable = {};
            scope.table1 = {}; //表1
            scope.table2 = {}; //表2
            scope.dataTable = null;
            scope.msg = null;  //错误提示
            scope.index = null; //tableIndex 表1 or 表2

            //下拉框的个数--字段的关联--init
            scope.dataSum = [0];

            //存储选择的字段关联的信息---init
            scope.dataFileds = [{}];

            //汇总分类的方式
            scope.counts = [
                {desc:'计数',value:'count'},
                {desc:'和值',value:'sum'},
                {desc:'最大值',value:'max'},
                {desc:'最小值',value:'min'},
                {desc:'平均值',value:'avg'},
                {desc:'分类',value:'group'}
            ];
            $rootScope.$on('clear_tableAggregate_EV',function(){
                //下拉框的个数--字段的关联--init
                scope.dataSum = [0];

                //存储选择的字段关联的信息---init
                scope.dataFileds = [{}];
            });
            $rootScope.$on("editTableAggregate_EV",function(e,data,index){
                $timeout(function(){
                    $(element).modal('show');
                },500);
                console.log(data);
                //表1
                if(index == 1){
                    scope.index = 1;
                    scope.table1.value = data;
                    getHasFiled(scope.table1.value.tbId, scope.table1.value.tableType, 1);


                }else if(index == 2){ //表2
                    scope.index = 2;
                    scope.table2.value = data;

                    getFiled(scope.table2.value.tbId, scope.table2.value.tableType, 2);
                }

            });
            /**
             * 获取字段
             * @param tbId
             * @param tableType
             * @param index  第几个表 表1 or 表2
             */
            function getFiled(tbId, tableType, index) {
                tools.get({
                    method: 'POST',
                    url: '/Ibm-Client/getSingleTable.htm',
                    data: {
                        tbId: tbId,
                        tableType: tableType
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            if (index == 1) {
                                scope.table1.filed = resp.value.columns;

                                angular.forEach(scope.dataHasFiled,function(item,index){
                                    angular.forEach(scope.table1.filed,function(item2){
                                        if(item.refColumnId == item2.columnId){
                                            scope.dataHasFiled[index].columnDesc = item2.columnDesc;
                                            return;
                                        }
                                    });

                                });
                                console.log('scope.table1.filed');console.log(scope.table1.filed);
                                console.log('scope.dataHasFiled');console.log(scope.dataHasFiled);

                                scope.dataTable = resp.value.columns;
                            } else if(index == 2) {
                                scope.table2.filed = resp.value.columns;
                                scope.dataTable = resp.value.columns;
                            }
                        }else{
                            $timeout(function(){
                                $(element).modal('hide');
//                            alert(resp.message);
                                $rootScope.$broadcast("MESSAGE_EV","数据异常，请找管理员联系。");
                                return;
                            },500);
                        }
                    }
                });
            }
            //获取已经有的汇总
            function getHasFiled(tbId, tableType, index){
                //下拉框的个数--字段的关联--init
                scope.dataSum = [0];

                //存储选择的字段关联的信息---init
                scope.dataFileds = [{}];
                tools.get({
                    method: 'POST',
                    url: '/Ibm-Client/getIbmAggregateFunction.htm',
                    data: {
                        tbId: tbId,
                        tableType: tableType
                    },
                    succ: function(resp){
                        if(resp.success){
                            var hasColumn = resp.value.table.columns;

                            scope.refTableDesc = resp.value.table.refTable.tableDesc;

                            console.log(hasColumn);


                            scope.dataHasFiled = [{}];
                            angular.forEach(hasColumn,function(item,index){
                                scope.dataHasFiled[index].count = item.aggregateType;
                                scope.dataHasFiled[index].filed = item.columnDesc;
                                scope.dataHasFiled[index].filedDesc = item.columnDesc;
                                scope.dataHasFiled[index].refColumnId = item.refColumnId;

                                scope.dataHasFiled.push({});
                            });

                            scope.dataHasFiled.splice(-1,1);
                            console.log('dataHasFiled');
                            console.log(scope.dataHasFiled);



                            scope.parentTable.tableType = resp.value.table.refTable.tableType;
                            scope.parentTable.tableDesc = resp.value.table.refTable.tableDesc;
                            scope.parentTable.tbId = resp.value.tables[1].tbId;
                            getFiled(resp.value.tables[1].tbId, resp.value.tables[1].tableType ,1);
                        }else{
                            $timeout(function(){
                                $(element).modal('hide');
//                            alert(resp.message);
                                $rootScope.$broadcast("MESSAGE_EV","数据异常，请找管理员联系。");
                                return;
                            },500);

                        }
                    }

                });
            }
            //增加字段
            scope.addSum = function () {
                scope.dataFileds.push({});
                scope.dataSum.push(scope.dataSum.length);
            };

            //删除字段
            scope.lessSum = function (index) {
                scope.dataSum.splice(index, 1);
                scope.dataFileds.splice(index, 1);
            };
            //scope.isGroup = false;
            scope.selectCount = function(index){
                scope.dataFileds[index].filedDesc = scope.dataFileds[index].filed;
                scope.dataFileds[index].isGroup = true;
            };

            //取消汇总
            scope.cancel = function () {
                $(element).modal('hide');

                scope.table1 = {}; //表1
                scope.table2 = {}; //表2
                scope.msg = null;  //错误提示
                //下拉框的个数--字段的关联--init
                scope.dataSum = [0];

                //存储选择的字段关联的信息---init
                scope.dataFileds = [{}];
                scope.index = null;
            };

            //确认汇总
            scope.ok = function(){

                if(scope.dataFileds[0].filed == null &&scope.dataFileds[0] != null){
                    scope.msg = '请选择字段';
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }

                if(scope.dataFileds[0].count == null &&scope.dataFileds[0] != null){
                    scope.msg = '请选择聚合方式';
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }

                for(var i=0;i<scope.dataFileds.length;i++){
                    for(var j=i+1;j<scope.dataFileds.length;j++){
                        if((scope.dataFileds[i].count == scope.dataFileds[j].count)&&(scope.dataFileds[j].count!=null) && (scope.dataFileds[i].filed == scope.dataFileds[j].filed) && (scope.dataFileds[j].filed != null)){
                            scope.msg = '该汇总分类已存在';
                            $timeout(function(){
                                scope.msg = null;
                            },2000);
                            return;
                        }
                    }
                    for(var k=0;k<scope.dataHasFiled.length;k++){
                        if((scope.dataFileds[i].count == scope.dataHasFiled[k].count) && (scope.dataFileds[i].filed == scope.dataHasFiled[k].filed)){
                            scope.msg = '该汇总分类已存在';
                            $timeout(function(){
                                scope.msg = null;
                            },2000);
                            return;
                        }
                    }

                }



                console.log(scope.dataFileds);
                console.log(scope.table1.filed);


                var json = {};
                //所有的字段选择信息----scope.dataFileds--从table中获取相应的值
                if(scope.index == 1){

                    json.refTbId = scope.parentTable.tbId;
                    json.refTableType = scope.parentTable.tableType;

                    angular.forEach(scope.dataFileds, function (item,index) {//数组json

                        angular.forEach(scope.table1.filed, function (itemleft) {//table1
                            if (item.filed && item.filed == itemleft.columnDesc) {
                                item.filedData = {};
                                item.filedData.columnType = itemleft.columnType;
                                item.filedData.columnId = itemleft.columnId;
                                item.filedData.fieldName = itemleft.fieldName;
                                return;
                            }
                        });
                    });
                }
                /*else if(scope.index == 2){

                    json.refTbId = scope.table2.value.tbId;
                    json.refTableType = scope.table2.value.tableType;

                    angular.forEach(scope.dataFileds, function (item) {//数组json
                        angular.forEach(scope.table2.filed, function (itemright) {//table1
                            if (item.filed == itemright.columnDesc) {
                                item.filedData = {};
                                item.filedData.columnType = itemright.columnType;
                                item.filedData.columnId = itemright.columnId;
                                item.filedData.fieldName = itemright.fieldName;

                                return;
                            }
                        });
                    });
                }*/


                json.tbId = scope.table1.value.tbId;
                json.columnDescs = '';
                json.fieldNames = '';
                json.aggregateTypes = '';
                json.columnTypes = '';
                json.refColumnIds = '';
                angular.forEach(scope.dataFileds,function(item,index){

                    if(item.filedData){ //去除空行的内容字段
                        json.fieldNames += item.filedData.fieldName+',';
                        json.aggregateTypes += item.count+',';

                        json.columnDescs += item.filedDesc+',';
                        json.columnTypes += item.filedData.columnType+',';
                        json.refColumnIds += item.filedData.columnId+',';
                    }

                });
                console.log(json);

                tools.get({
                    url: '/Ibm-Client/addAggregateColumns.htm',
                    data: json,
                    succ: function(resp){
                        if(resp.success){
                            $rootScope.$broadcast('update_TableAggregate',scope.table1.value.tbId, scope.table1.value.tableType);
                            $rootScope.$broadcast('MESSAGE_EV','编辑成功');
                        }else{
                            $rootScope.$broadcast('MESSAGE_EV','编辑失败');
//                            alert(resp.message);
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
                        }
                    }
                });
                $(element).modal('hide');

            };

        }
    }
}]);

